package com.xiaozhi.exception;

/**
 * 重试失败异常
 * 当重试机制用尽所有尝试后仍然失败时抛出此异常
 */
public class RetryFailedException extends RuntimeException {
    
    private final String operationName;
    private final int maxRetries;
    private final Exception lastException;
    
    public RetryFailedException(String operationName, int maxRetries, Exception lastException) {
        super(String.format("操作 '%s' 在 %d 次重试后仍然失败: %s", 
                operationName, maxRetries, 
                lastException != null ? lastException.getMessage() : "未知错误"));
        this.operationName = operationName;
        this.maxRetries = maxRetries;
        this.lastException = lastException;
    }
    
    public String getOperationName() {
        return operationName;
    }
    
    public int getMaxRetries() {
        return maxRetries;
    }
    
    public Exception getLastException() {
        return lastException;
    }
    
    /**
     * 获取原始异常的错误类型
     */
    public String getErrorType() {
        if (lastException == null) {
            return "UNKNOWN_ERROR";
        }
        
        String message = lastException.getMessage();
        if (message == null) {
            return "UNKNOWN_ERROR";
        }
        
        String lowerMessage = message.toLowerCase();
        
        // 网络相关错误
        if (lowerMessage.contains("timeout") || 
            lowerMessage.contains("connection") ||
            lowerMessage.contains("network") ||
            lowerMessage.contains("socket")) {
            return "NETWORK_ERROR";
        }
        
        // 服务器错误
        if (lowerMessage.contains("500") || 
            lowerMessage.contains("502") ||
            lowerMessage.contains("503") ||
            lowerMessage.contains("504")) {
            return "SERVER_ERROR";
        }
        
        // 频率限制
        if (lowerMessage.contains("rate limit") || 
            lowerMessage.contains("too many requests") ||
            lowerMessage.contains("429")) {
            return "RATE_LIMIT_ERROR";
        }
        
        // API密钥错误
        if (lowerMessage.contains("api key") ||
            lowerMessage.contains("authentication") ||
            lowerMessage.contains("unauthorized") ||
            lowerMessage.contains("401") ||
            lowerMessage.contains("403")) {
            return "AUTH_ERROR";
        }
        
        return "UNKNOWN_ERROR";
    }
    
    /**
     * 获取用户友好的错误消息
     */
    public String getUserFriendlyMessage() {
        String errorType = getErrorType();
        
        switch (errorType) {
            case "NETWORK_ERROR":
                return "网络连接异常，请检查网络设置后重试";
            case "SERVER_ERROR":
                return "服务器暂时不可用，请稍后重试";
            case "RATE_LIMIT_ERROR":
                return "请求过于频繁，请稍后重试";
            case "AUTH_ERROR":
                return "服务配置异常，请联系管理员";
            default:
                return "服务暂时不可用，请稍后重试";
        }
    }
}